<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>
        {{ $t('report.staffEventTable.title1') }}
        <el-popover trigger="hover">
          {{$t('report.staffCategoryChart.text2')}}：{{$t('report.staffEventTable.title15')}}<br />
          {{$t('common.base.usualStatus.unFinish')}}：{{$t('report.staffEventTable.title22')}}<br />
          {{$t('common.base.todayFinished')}}：{{ $t('report.staffEventTable.title17') }}<br />
          {{$t('report.staffEventTable.title4')}}：{{ $t('report.staffEventTable.title18') }}<br />
          {{$t('report.staffEventTable.title5')}}：{{ $t('report.staffEventTable.title19') }}<br />
          {{$t('report.staffEventTable.title6')}}：{{ $t('report.staffEventTable.title20') }}<br />
          {{$t('report.staffEventTable.title7')}}：{{ $t('report.staffEventTable.title21') }}<br />
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="ignoreDeleted" @input="chooseCategoryDeleted">{{$t('report.staffEventTable.title2')}}</base-checkbox>
      </div>
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="ignoreNull" @input="chooseIgnore">{{$t('report.staffCategoryChart.text2')}}</base-checkbox>
      </div>

      <biz-team-select multiple is-auto-select-child collapse class="stats-team-select biz-team-select" :value="tag" @input="chooseTeam" :fetch-func="fetchTeam" @remove="clearTeam"/>


      <div class="stats-form-group">
        <input type="text" :placeholder="$t('report.staffEventTable.placeholder')" v-model="keyword" @input="updateServerName" style="line-height: 20px;">
      </div>
      <div class="stats-form-group">
        <el-dropdown :hide-on-click="false" trigger="click" :show-timeout="150">
          <button type="button" class="stats-btn-text">{{$t('common.base.choiceCol')}} <i class="el-icon-arrow-down el-icon--right"></i></button>

          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="column in columns" :key="column.field">
              <el-checkbox class="dropdown-item" :value="column.show" @input="chooseColnum(column)" :disabled="column.field == 'displayName'">{{column.label}}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="stats-panel-body">
      <el-table :data="filterRows" class="stats-table">
        <template v-for="col in showColumns" >
          <el-table-column :label="$t('report.staffEventTable.title3')" :key="col.field" v-if="col.field === 'displayName'">
            <template slot-scope="scope">
              <a href="#" class="view-user-detail-btn" @click="openDetail(scope.row, `/security/user/view/${scope.row.userId}`)">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.staffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.displayName}}
                </template>
              </a>
            </template> 
          </el-table-column>

          <el-table-column :label="`${$t('report.staffEventTable.title16')}(${$t('common.base.yuan')})`" :key="col.field" v-else-if="col.field === 'monthCost'">
            <template slot-scope="scope">
              {{scope.row.monthCost.toFixed(2)}}
            </template>
          </el-table-column>

          <el-table-column :label="col.label" :prop="col.field" :key="col.field" sortable v-else></el-table-column>
        </template>
        <div class="stats-table-expand" slot="append" :class="{'stats-table-isExpand': expand}" v-if="rows.length > 10 && !keyword">
          <button type="button" @click="expand = !expand">
            <i class="iconfont icon-zhankaisanjiao"></i> {{expand ? $t('report.staffEventTable.label1') : $t('report.staffEventTable.label2')}}
          </button>
        </div>
      </el-table>

    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import http from 'src/util/HttpUtil';
import StorageUtil from 'src/util/storageUtil';

import Loading from 'packages/BaseLoading';
import BaseTable from 'packages/BaseTable';
import BaseCheckbox from 'packages/BaseCheckbox.vue';
import _ from 'lodash';
import { isBasicEditionHidePay } from '@shb-lib/version';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

const STATS_COLUMN_KEY = 'stats_staff_task_list_colnum';
let that;

export default {
  name: 'staff-event-table',
  props: {
    chartType: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      isOpenData,
      tag: [],
      rows: [],
      ignoreNull: true,
      teamId: '',
      columns: this.buildColumns(),
      keyword: '',
      expand: false,
      templates: [],
      ignoreDeleted: true
    }
  },
  computed: {
    filterRows(){
      let rows = this.rows.filter(row => {
        return row?.displayName?.toLowerCase().indexOf(this.keyword.toLowerCase()) >= 0
      });
      
      if(!this.expand && rows.length > 10) rows = rows.splice(0, 10);
      return rows;
    },
    showColumns(){
      if (this.isBasicEditionHidePay) {
        return this.columns.filter(col => col.show && col.field !== 'monthCost')
      }

      return this.columns.filter(col => col.show);
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
  },
  filters: {
    template(taskType) {
      if (!taskType || taskType == t('report.staffEventTable.label3')) return t('report.staffEventTable.label3');
      let res = that.templates.filter(item => item.taskTypeId == taskType)[0]
      return res.taskTypeName
    }
  },
  methods: {
    clearTeam(value = []){
      this.tag = value;      
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.teamId = ids.join(',');
      this.renderTable();
    },

    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    chooseColnum(column){
      this.$emit('trackEvent', 'chooseColumn');

      column.show = !column.show;

      let data = {};
      this.columns.forEach(item => data[item.field] = item.show)
      StorageUtil.save(STATS_COLUMN_KEY, data);
    },
    buildColumns(){
      let localData = StorageUtil.get(STATS_COLUMN_KEY) || {};

      let columns = [
        {
          label: this.$t('report.staffEventTable.title3'),
          field: 'displayName',
          show: true
        },
        {
          label: this.$t('common.base.usualStatus.unFinish'),
          field: 'allocatedCount',
          show: true
        },
        {
          label: this.$t('common.base.todayFinished'),
          field: 'todayFinish',
          show: true
        },
        {
          label: this.$t('report.staffEventTable.title4'),
          field: 'weekFinish',
          show: true
        },
        {
          label: this.$t('report.staffEventTable.title5'),
          field: 'monthFinish',
          show: true
        },
        {
          label: this.$t('report.staffEventTable.title6'),
          field: 'satisfication',
          show: true
        },
        {
          label: this.$t('report.staffEventTable.title7'),
          field: 'unSatisfication',
          show: true
        }
      ];

      columns.forEach(column => {
        let isShow = localData[column.field];
        if(typeof isShow == 'boolean') column.show = isShow;
      })

      return columns;
    },
    async renderTable(){
      try {
        let instance = Loading.show(this.$el);
        let rows = await this.fetchData();
        instance.hide();
        this.rows = rows || [];  
      } catch (error) {
        console.log(error)
      }
    },
    chooseIgnore(value){
      this.ignoreNull = value;
      this.renderTable();
    },
    chooseCategoryDeleted(value) {
      this.ignoreDeleted = value;
      this.renderTable();
    },
    chooseTeam(value){
      this.$emit('trackEvent', 'chooseTeam');
      this.tag = value;
      
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.teamId = ids.join(',');

      this.renderTable();
      // 部门埋点
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    fetchData(){
      let params = {
        teamId: this.teamId,
        ignoreNull: this.ignoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      return http.post('/api/report/outside/stats/station/userEventByTag', params);
    },
    openDetail(row, url){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `userView_${ row.userId}`, 
      //   title: '用户详情', 
      //   close: true, 
      //   url,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: row.userId,
        fromId
      })
    },
    // track TalkingData Event
    updateServerName: _.debounce(function () {
      this.$emit('trackEvent', 'updateServerName')
      this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_MANAGER_SEARCH', this.$track)
    }, 1000)
  },
  mounted(){
    this.renderTable();
  },
  beforeCreate () {
    that = this
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox,
    [BaseTable.name]: BaseTable
  }
}
</script>

